<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Web3.js Test</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.3.5/dist/web3.min.js"></script>
</head>

<body>
<h2>Web3.js Test</h2>
<hr />

<div>
    <div>
        <button id="web3_clientVersion">web3_clientVersion</button>
    </div>
</div>

<script>
    function showResult(node, msg) {
        node.parent().append(" <span>" + msg + "</span>");
    }

    jQuery("#web3_clientVersion").click(async function () {

        if (typeof window.ethereum !== 'undefined') {
            let addr=await ethereum.request({ method: 'eth_requestAccounts' });//授权连接钱包
            console.log('用户钱包地址:',addr[0]);
        }else{
            console.log('未安装钱包插件！');
        }


        if(typeof web3 !=='undefined'){ //检查是否已有web3实例
            web3=new Web3(web3.currentProvider);
        }else{
            //否则就连接到给出节点
            web3=new Web3();
            web3.setProvider(new Web3.providers.WebsocketProvider("ws://localhost:8546"));
        }

//通过查询创世区块来判断是否连接成功
        web3.eth.getBlock(0, function(error, result){
            if(!error)
                console.log("connection should be succeed");
            else
                console.log("something wrong,the connection might be failed");
        })

//get node_accounts  获取节点下的账户
        let account0;
        web3.eth.getAccounts(function(error, result){
            if(!error){
                account0=result[0];
                //console.log(account0);
                console.log("accounts:"+result);
            }
            else{
                console.log("failed to get Accoutns");
            }
        })

//get balance  获取指定账户下的余额
        web3.eth.getBalance('0x2EC12C8e3a8a0df6EdD448688e6EE0E0132ED801').then(function(balance){
            console.log('balance:',balance);
        })
    });
</script>
</body>
